package zj.com.fragments;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import zj.com.activities.CaptureActivity;
import zj.com.activities.ChoiceJcxActivity;
import zj.com.activities.DzgDetailActivity;
import zj.com.activities.JcxDetailActivity;
import zj.com.adapter.DzgDetailAdapter;
import zj.com.adapter.JcxAdapter;
import zj.com.app.ZjApplication;
import zj.com.db.DBUtil;
import zj.com.model.Dic;
import zj.com.model.Dzg;
import zj.com.model.DzgDetail;
import zj.com.model.DzgDetailDB;
import zj.com.model.DzgInspectItemDB;
import zj.com.model.DzgInspectTask;
import zj.com.model.InspectContent;
import zj.com.model.InspectItem;
import zj.com.model.JcxDB;
import zj.com.model.JcxDetailDB;
import zj.com.model.PgScan;
import zj.com.model.UploadFile;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.Constants;
import zj.com.util.DateUtil;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.zj.R;

/**

 */
public class DzgJcxFragment extends Fragment{


    public ListView listView;
    public TextView rw_tv,end_date_tv,upload_tv;
    public DzgDetailAdapter adapter;
    public List<DzgInspectTask> list;
    public DbManager dbManager;
    public String InspectionID="";
    public String InspectionItemID ="";
    public Dzg dzg;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dzg_jcx, container, false);
        initView(view);
        return view;
    }


    public void initView(View view){
        list = new ArrayList<DzgInspectTask>();
        dbManager = DBUtil.getInstance(getActivity()).getDBManager();
        adapter = new DzgDetailAdapter(list,getActivity());
        rw_tv = (TextView) view.findViewById(R.id.rw_value_tv);
        end_date_tv = (TextView) view.findViewById(R.id.end_date_value_tv);
        listView = (ListView) view.findViewById(R.id.listView);
        listView.setAdapter(adapter);

        upload_tv = (TextView) view.findViewById(R.id.upload_tv);
        upload_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImg();
            }
        });
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        InspectionID = DzgDetailActivity.InspectionID;
        InspectionItemID = DzgDetailActivity.InspectionItemID;
        dzg = DzgDetailActivity.dzg;
        if (isVisibleToUser) {
        if(!TextUtils.isEmpty(InspectionID)){
            LogUtils.getInstance().error(" 推送传过来的");
            obtainData(InspectionID,InspectionItemID);
        }else{

            LogUtils.getInstance().error(" 从列表传过来的");
            if( ZjApplication.dzgDetailDB == null){
                obtainData(dzg.getInspectionID() + "", dzg.getInspectItemID() + "");
            }

        }
        }
    }


    public void obtainData(final String inspectionID, final String inspectionItemID){


        dialog = DialogUtil.createProgressDialog(getActivity(), "提示", "数据获取中..");
        NetManager.getInstance(getActivity()).GetToBeRepairedInspectionDetail(inspectionID, inspectionItemID, new OnResponseListener<DzgDetail>() {
            @Override
            public void onComplete(boolean isOK, DzgDetail detail, int errorCode, String errorMsg) {

                try {

                    if (!TextUtils.isEmpty(InspectionID) && detail == null) {

                        Toast.makeText(getActivity(), "该任务已处理", Toast.LENGTH_SHORT).show();
                        getActivity().finish();
                        return;

                    }

                    if (detail != null) {
                        ZjApplication.dzgDetail = detail;
                        DzgDetailDB detailDB = new DzgDetailDB();
                        if (dzg != null) {
                            detailDB.setInspectionID(dzg.getInspectionID());
                            detailDB.setInspectionItemID(dzg.getInspectItemID());
                        } else {
                            detailDB.setInspectionID(Integer.parseInt(inspectionID));
                            detailDB.setInspectionItemID(Integer.parseInt(inspectionItemID));
                        }

                        detailDB.setRiskID(detail.getRiskID());
                        ZjApplication.dzgDetailDB = detailDB;
                        String taskName = detail.getInspectTaskName();
                        if (taskName != null && taskName.equals("null")) {
                            taskName = "";
                        }

                        rw_tv.setText(taskName);
                        String deadLine = detail.getDeadLine();

                        if (deadLine != null && deadLine.equals("null")) {
                            deadLine = "";
                        }

                        deadLine = deadLine.replace("T", " ");
                        end_date_tv.setText(DateUtil.formatStrimgDate2(deadLine));
                        list = detail.getTaskList();
                        int count = 0;
                        if(list != null){
                            detailDB.setInpsect_count(list.size());
                        }

                        adapter.setDataChange(list);

                    } else {
                        LogUtils.getInstance().error("detail is null");

                    }
                } catch (Exception e) {

                    LogUtils.getInstance().error(e.toString());
                }
                dialog.dismiss();
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();

            }
        });
    }



    int count = 0;
    public ProgressDialog dialog;
    public void uploadImg(){


        if(dzg == null || list == null){
            Toast.makeText(getActivity(), "提交失败", Toast.LENGTH_SHORT).show();
            return;
        }
        final DbManager dbManager = DBUtil.getInstance(getActivity()).getDBManager();

        count = 0;
        try{
            if (ZjApplication.dzgDetailDB != null) {
                DzgDetailDB detail =  dbManager.selector(DzgDetailDB.class).where("inspection_id", "=", ZjApplication.dzgDetailDB.getInspectionID()).and("inspectionitem_id", "=", ZjApplication.dzgDetailDB.getInspectionItemID()).findFirst();
                if(detail == null){
                    ZjApplication.dzgDetailDB.setId(UUID.randomUUID().toString());
                    detail = ZjApplication.dzgDetailDB;
                }
                dbManager.saveOrUpdate(detail);
            }
            final List<DzgInspectItemDB> items =  dbManager.selector(DzgInspectItemDB.class).where("inspectid", "=", dzg.getInspectionID()).findAll();

            if(items != null && list.size() == items.size()){

                for(final DzgInspectItemDB item:items){
                    String img =  item.getImgs();
                    dialog = DialogUtil.createProgressDialog(getActivity(),"提示","上传图片中..");
                    NetManager.getInstance(getActivity()).newUploadImg(img, new OnResponseListener<List<UploadFile>>() {
                        @Override
                        public void onComplete(boolean isOK, List<UploadFile> result, int errorCode, String errorMsg) {

                            if(isOK){
                                count ++;
                                dialog.setMessage("上传数据中...");
                                StringBuffer sb = new StringBuffer();
                                for(UploadFile file:result){
                                    sb.append(file.getResourceId());
                                    sb.append(",");
                                }
                                item.setUploadImgs(sb.toString());
                                try {
                                    dbManager.saveOrUpdate(item);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }

                                if(count == items.size()){
                                    doSumbitData();
                                }

                            }else{
                                dialog.dismiss();
                                Toast.makeText(getActivity(), " 上传失败", Toast.LENGTH_SHORT).show();

                            }
                        }

                        @Override
                        public void onInternError(int errorCode, String errorMessage) {
                            dialog.dismiss();

                            Toast.makeText(getActivity(), " 上传失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }else{

                Toast.makeText(getActivity(), "请填写相应的整改项内容", Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){

        }


    }

    public void doSumbitData(){

        NetManager.getInstance(getActivity()).AddRepairRecord(dzg, new OnResponseListener<Dzg>() {
            @Override
            public void onComplete(boolean isOK, Dzg result, int errorCode, String errorMsg) {


                if (isOK) {
                    dialog.dismiss();

                    DbManager dbManager = DBUtil.getInstance(getActivity()).getDBManager();
                    try {
                        DzgDetailDB detail = dbManager.selector(DzgDetailDB.class).where("inspection_id", "=", dzg.getInspectionID()).where("inspectionitem_id", "=", dzg.getInspectItemID()).findFirst();
                        if (detail != null) {
                            dbManager.delete(detail);

                        }
                        List<DzgInspectItemDB> items = dbManager.selector(DzgInspectItemDB.class).where("inspectionitem_id", "=", dzg.getInspectItemID()).findAll();
                        if (items != null) {
                            for (DzgInspectItemDB item : items) {
                                dbManager.delete(item);
                            }
                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }

                    ZjApplication.dzgInspectItemDB = null;
                    ZjApplication.dzgDetailDB = null;
                    Toast.makeText(getActivity(), " 提交成功", Toast.LENGTH_SHORT).show();
                    getActivity().finish();

                } else {
                    dialog.dismiss();
                    Toast.makeText(getActivity(), " 提交失败", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();
                Toast.makeText(getActivity(), " 提交失败", Toast.LENGTH_SHORT).show();

            }
        });


    }


}
